/**
 * 
 */
package com.adkfp.action;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.adkfp.bean.ADKActimeBean;
//import com.acs.instructions.ACAuthority;
//import com.acs.instructions.OpenDoor;
//import com.acs.net.ADKClient;
//import com.acs.net.ADKPublic;
//import com.acs.receive.impl.PkgCardInfo;
import com.adkfp.bean.ADKControllerBean;
import com.adkfp.bean.ADKPowerGroupDoorBean;
import com.adkfp.bean.ADKUserInfoBean;
import com.adkfp.common.ControllerTime;
import com.adkfp.common.UserRight;
import com.adkfp.service.IADKActimeService;
//import com.adkfp.hardware.Test03;
import com.adkfp.service.IADKControllerService;
import com.adkfp.service.IADKPowerGroupDoorService;
import com.adkfp.utils.JsonUtil;
import com.adkfp.utils.LayuiUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;




/**
 * @author qwertyuiop
 *
 */
@Controller
@RequestMapping("aDKController")
public class ADKControllerAction {
	@Resource(name="aDKActimeService")
	private IADKActimeService aDKActimeService;

	@Resource(name="aDKControllerService")
	private IADKControllerService aDKControllerService;
	
	@Resource(name="aDKPowerGroupDoorService")
	private IADKPowerGroupDoorService aDKPowerGroupDoorService;
	//跳转页面
	@RequestMapping("index")
	public String index() {
		return "aDKController/ControllerTable";
	}
	
	

	
	//查询所有记录
	@RequestMapping("selectAll")
	@ResponseBody
	public Object selectAll(ADKControllerBean bean,HttpServletRequest request) {
		List<ADKControllerBean> list = new ArrayList<>();
		list = aDKControllerService.findByCondition(bean);
		long count = aDKControllerService.findByConditionCount(bean);
		return LayuiUtil.data(count, list);
	}

	
	//用于权限组设置-门权限 @C
		@RequestMapping("selectAllu")
		@ResponseBody
		public Object selectAllu(ADKPowerGroupDoorBean beanAPGD,ADKControllerBean bean,HttpServletRequest request,Model model,String groupID ) {
			System.out.println("----设置权限组中的门权限的groupID是----"+groupID);
			//每个权限组已经保存的APGD数据done
			List<ADKPowerGroupDoorBean> listAPGD = new ArrayList<>();
			beanAPGD.setGroupID(Integer.parseInt(groupID));
			listAPGD = aDKPowerGroupDoorService.findByCondition(beanAPGD);
			
			
			//全部待添加的数据
			List<ADKControllerBean> listAll = new ArrayList<>();
			listAll = aDKControllerService.ufindByCondition(bean);//全部adkdoor中原返回的数据
			List<ADKControllerBean> listsend = new ArrayList<>();
			
			System.out.println("权限组保存中的数据测试");
			System.out.println(listAll.size());
			System.out.println(listAPGD.size());//done
			
			//清除
			boolean sendflag = false;//默认没有
			if(listAPGD.size() != listAll.size()) {
				for (int i = 0; i < listAll.size(); i++){
					for(int j = 0;j < listAPGD.size(); j++) {
						if(listAll.get(i).getCtrlAddr() == listAPGD.get(j).getCtrlAddr() && listAll.get(i).getDooraddr()== listAPGD.get(j).getDoorAddr()) {
							//将未添加的数据放到传递list中
							sendflag = true;
						}
					}
					if(!sendflag) {
						listsend.add(listAll.get(i));
					}
					sendflag = false;//@C 注意初始化位置 有优化空间
				}
			}else {
				//已经全部选择，则返回空list
				listsend.clear();
			}
			System.out.println(listsend.size());
			
			
			//全部数据以及封装时间组
			//下拉框数据
			List<ADKActimeBean> selectlist =aDKActimeService.findtime();//下拉框时间组数据
			List<String> timetemplist = new ArrayList<>();//时间组list
				//System.out.println("-----下拉框----");
				//先设置显示默认值
				for (int i = 0; i < selectlist.size(); i++) {
					timetemplist.add(selectlist.get(i).getTimeName());
				}//done
				
				
			System.out.println("集合添加时间组");
			
			//设置时间组@C
			if(listsend.size()>0) {
				for (int i = 0; i < listsend.size(); i++) {
					//添加时间组
					listsend.get(i).setTimeName(timetemplist);
					//System.out.println(list.get(i));//包括时间组的数据
				}
			}
			//long count = aDKControllerService.ufindByConditionCount(bean);分页用
			//return LayuiUtil.data(count, list);//分页用
			return listsend;
		}
		
		
		//增加门权限保存方法@C
		@RequestMapping("addDoorPowerGroup")
		@ResponseBody
		public String addDoorPowerGroup(@RequestBody String jsonString,HttpServletRequest request,Integer GroupID) {
			List<ADKControllerBean> adkCBList = new ArrayList<>();
			
			System.out.println(GroupID);
			System.out.println("进入门权限add方法");
			if(GroupID == null ) {
				GroupID = 1;
			}
			System.out.println("ID:"+GroupID);
			System.out.println(jsonString);
			
			JSONArray json = JSONArray.fromObject(jsonString);//先将对象转成json数组
			for (int i = 0; i < json.size(); i++) {
				if(!Objects.equals(json.getJSONObject(i).toString(), "null")) {//都是json字符串，需要以字符串形式判空，而不是对象形式
					JSONObject jsob = json.getJSONObject(i);
					aDKControllerService.insertDoorPowerGroup((Integer)jsob.getInt("netGroupID"),GroupID, (Integer)jsob.getInt("subPointID"),jsob.getInt("ctrlAddr"),jsob.getInt("dooraddr"),jsob.getInt("timeName")+1);
				}
			}
			return "success:success";
		}
		
	
	//用于权限组设置-门权限
		@RequestMapping("selectAllDoor")
		@ResponseBody
		public void selectAllDoor(HttpServletRequest request,ADKPowerGroupDoorBean  pgdbean/*,String groupID*/) {
			//List<ADKControllerBean> list = new ArrayList<>();
			//list = aDKControllerService.ufindByCondition(bean);
			//System.out.println("---------用于权限组设置-门权限----的groupID是"+groupID);
		    //pgdbean.setGroupID(Integer.parseInt("1"));
		    System.out.println("集合的内容是-----"+pgdbean);
			aDKPowerGroupDoorService.insert(pgdbean);
			//pgdbean.setGroupID(Integer.parseInt(groupID));
			List<ADKPowerGroupDoorBean> list=new ArrayList<>();
			list=aDKPowerGroupDoorService.findByCondition(pgdbean);
			long count = aDKPowerGroupDoorService.findByConditionCount(pgdbean);
		}
	
	
	//修改控制器
	@RequestMapping("addController")
	@ResponseBody
	public void addController(ADKControllerBean bean,HttpServletRequest request) throws ClassNotFoundException, SQLException, IOException {
		System.err.println("---++----取值"+bean.getaPBEnable());
		System.err.println("---++----取值ip地址是："+bean.getiP());
		System.err.println("---++----取值端口号是："+bean.getPort());
		//Test03 t=new Test03();
		//t.open();
		//Controllerhard(bean.getiP(),bean.getPort());
		
		if(bean.getaPBEnable()==null) {
			bean.setaPBEnable(0);
		}
		if(bean.getBoxLock()==null) {
			bean.setBoxLock(0);
		}
		if(bean.getInterlockDoor1()==null) {
			bean.setInterlockDoor1(0);
		}
		if(bean.getInterlockDoor2()==null) {
			bean.setInterlockDoor2(0);
		}
        if(bean.getInterlockDoor3()==null) {
        	bean.setInterlockDoor3(0);
        }
        if(bean.getInterlockDoor4()==null) {
        	bean.setInterlockDoor4(0);
        }
        if(bean.getSensorEnable1()==null) {
        	bean.setSensorEnable1(0);
        }
        if(bean.getSensorEnable2()==null) {
        	bean.setSensorEnable2(0);
        }
        if(bean.getSensorEnable3()==null) {
        	bean.setSensorEnable3(0);
        }
        if(bean.getSensorEnable4()==null) {
        	bean.setSensorEnable4(0);
        }
        if(bean.getDoubleAction1()==null) {
        	bean.setDoubleAction1(0);
        }
        if(bean.getDoubleAction2()==null) {
        	bean.setDoubleAction2(0);
        }
        System.out.println("==========================");
        System.err.println("=====+++===="+bean.getDoubleAction1());
        String qiyong=request.getParameter("qiyong");
        System.err.println("---启用----"+qiyong);
        String starttime1=null;
        String endtime1=null;
        String starttime2=null;
        String endtime2=null;
        String starttime3=null;
        String endtime3=null;
        String starttime4=null;
        String endtime4=null;
        String starttime5=null;
        String endtime5=null;
        String starttime6=null;
        String endtime6=null;
        String starttime7=null;
        String endtime7=null;
        if(qiyong==null) {
       
        	starttime1="0000";
       	 endtime1="0000";
       	
       	starttime2="0000";
       	 endtime2="0000";
       	
       	 starttime3="0000";
       	 endtime3="0000";
       	
       	 starttime4="0000";
       	 endtime4="0000";
       	
       	 starttime5="0000";
       	 endtime5="0000";
       	
       	 starttime6="0000";
       	 endtime6="0000";
       	
       	 starttime7="0000";
       	 endtime7="0000";
        
        }else {
        	//String starttime1=request.getParameter("starttime1");
            String[] ss1=request.getParameter("starttime1").split(":");
             starttime1=ss1[0]+ss1[1];
            //System.err.println("---====---"+starttime1);
            String[] ss2=request.getParameter("endtime1").split(":");
            endtime1=ss2[0]+ss2[1];
            
            String[] ss3=request.getParameter("starttime2").split(":");
            starttime2=ss3[0]+ss3[1];
            String[] ss4=request.getParameter("endtime2").split(":");
            endtime2=ss4[0]+ss4[1];
            
            String[] ss5=request.getParameter("starttime3").split(":");
             starttime3=ss5[0]+ss5[1];
            String[] ss6=request.getParameter("endtime3").split(":");
            endtime3=ss6[0]+ss6[1];
            
            String[] ss7=request.getParameter("starttime4").split(":");
            starttime4=ss7[0]+ss7[1];
            String[] ss8=request.getParameter("endtime4").split(":");
            endtime4=ss8[0]+ss8[1];
            
            String[] ss9=request.getParameter("starttime5").split(":");
            starttime5=ss9[0]+ss9[1];
            String[] ss10=request.getParameter("endtime5").split(":");
            endtime5=ss10[0]+ss10[1];

            String[] ss11=request.getParameter("starttime6").split(":");
            starttime6=ss11[0]+ss11[1];
            String[] ss12=request.getParameter("endtime6").split(":");
            endtime6=ss12[0]+ss12[1];
            
            String[] ss13=request.getParameter("starttime7").split(":");
            starttime7=ss13[0]+ss13[1];
            String[] ss14=request.getParameter("endtime7").split(":");
            endtime7=ss14[0]+ss14[1];
        }
        

		   JSONObject jsonObject = new JSONObject();
		   //星期日
		   jsonObject.put("starttime1", starttime1);
		   jsonObject.put("endtime1", endtime1);
		   //星期一
		   jsonObject.put("starttime2", starttime2);
		   jsonObject.put("endtime2", endtime2);
		   //星期二
		   jsonObject.put("starttime3", starttime3);
		   jsonObject.put("endtime3", endtime3);
		   //星期三
		   jsonObject.put("starttime4", starttime4);
		   jsonObject.put("endtime4", endtime4);
		  //星期四
		   jsonObject.put("starttime5", starttime5);
		   jsonObject.put("endtime5", endtime5);
		  //星期五
		   jsonObject.put("starttime6", starttime6);
		   jsonObject.put("endtime6", endtime6);
		  //星期六
		   jsonObject.put("starttime7", starttime7);
		   jsonObject.put("endtime7", endtime7);
		   
		String s=ControllerTime.pack(jsonObject);
		System.err.println("----===+++---"+s);
		bean.setWeekHoliday(s);
        
		if(bean.getAutoID()!=null && bean.getAutoID()!=0) {
			aDKControllerService.update(bean);
			
			
			InputStream in =  this.getClass().getClassLoader().getResourceAsStream("/database.properties");
			Properties properties = new Properties();
			try {
				properties.load(in);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//获取key对应的value值
			String dbdriver = properties.getProperty("jdbc.driverClass");//"com.mysql.jdbc.Driver");
			String dbhost =properties.getProperty("jdbc.jdbcUrl") ;//"jdbc:mysql://192.168.0.198:3306/qudao";
			String dbuser = properties.getProperty("jdbc.user","root");
			String dbpassword = properties.getProperty("jdbc.password", "123456");
			UserRight right = new UserRight(dbdriver,dbhost,dbuser,dbpassword);
			System.out.println("控制器的autoid是"+bean.getAutoID());
		    //right.getCtrlParamter(bean.getAutoID());
			//System.err.println(b);
		    
		    
		
	
		}
		
		

	}
	
	
/*	//硬件控制器——hardware
	public  void  Controllerhard(String ip,Integer port){
		//ADKClient ack=new ADKClient("192.168.0.131", 5768,2000);
		System.err.println("---++----硬件控制器——hardwareip地址是："+ip);
		System.err.println("---++----硬件控制器——hardware端口号是："+port);
		ADKClient ack=new ADKClient(ip,port,2000);
		ack.Connect();
		OpenDoor od=new OpenDoor();
		ack.execute(od);
		//System.out.println(String.format("0x%04x", DataLen));
		
		ACAuthority aca=new ACAuthority();
		PkgCardInfo ac=new PkgCardInfo();
		ac.cardCnt=1;//用户数量
		ac.er[0].setCardId(123, 1);
		ac.er[0].setDoor((byte)1,(byte)1,(byte)1,(byte)1);
		aca.setAci(ac);
		ack.execute(aca);
		//System.out.println(String.format("0x%04x", DataLen));
		
		//ack.open(b,DataLen);
		byte[] ret= ack.getDatabuffer();
		ADKPublic.printBytes(ret, ack.getDataLen());
		ack.DisConnect();
	}
	*/
	
	//跳转增加页面
	@RequestMapping("index1")
	public String index1() {
		return "aDKController/addController";
	}
	
	//增加控制器
	@RequestMapping("Controlleradd")
	@ResponseBody
	public void Controlleradd(ADKControllerBean bean) {
		
	int ctrladdr= aDKControllerService.selectMax()+1;
	
	System.out.println("----------ctrladdr-----------"+ctrladdr);
		//bean.setCtrlAddr(ctrlAddr);
	bean.setCtrlAddr(ctrladdr);
		aDKControllerService.insert(bean);
	}
	
	
	//用于修改页面(查找id)
		@RequestMapping("findId")
		public String findId(HttpServletRequest request,String id,String ctrlAddr,ADKControllerBean controllerbean) {
			//System.out.println("id------"+id);
			if(id != null && !id.equals("")) {
			     controllerbean=aDKControllerService.findById(Integer.parseInt(id));
			}
			//System.out.println("ctrlAddr-----------"+ctrlAddr);
			request.setAttribute("kongzhi",controllerbean);
			request.setAttribute("wk",ControllerTime.unpack(controllerbean.getWeekHoliday()));
			return "aDKController/Controller";
		}
		
		//删除控制器
		@RequestMapping("deletecontroller")
		@ResponseBody
		public String deletecontroller(@RequestParam("op")String op, @RequestParam("data")String data) {
			String f = "";
			if(data!=null&&!data.equals("")) {
				List<ADKControllerBean> list = JsonUtil.getList4Json(data, ADKControllerBean.class);
				for (ADKControllerBean bean : list) {
					aDKControllerService.delete(bean.getAutoID());
				}
				f = "删除成功";
			}
			return f;
		}
	
	//跳转控制器设置页面
	@RequestMapping("Controller")
	public String Controller() {
		return "aDKController/Controller";
	}
	
	@RequestMapping("findId2")
	public String findId2() {
		return "aDKActime/actimelist";
	}
	//用于跳转卡片管理页面
		@RequestMapping("findId1")
		public String findId1(HttpServletRequest request,String ctrlAddr,ADKControllerBean bean) {
			if(bean.getAutoID() != null && !bean.getAutoID().equals("")) {
				bean=aDKControllerService.finduseridById(Integer.parseInt(ctrlAddr));
			}
			//System.out.println("hhhhhh---------------aaaa----------"+ctrlAddr);
			request.setAttribute("userid",bean);
			return "aDKActime/actimelist";
		}
	
}
